package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDate;
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.MeterData;
import com.ruoyi.system.service.IMeterDataService;

/**
 * 电表数据Controller
 * 
 * @author ruoyi
 * @date 2023-05-20
 */
@Controller
@RequestMapping("/system/meterdata")
public class MeterDataController extends BaseController
{
    private String prefix = "system/meterdata";

    @Autowired
    private IMeterDataService meterDataService;

    @RequiresPermissions("system:meterdata:view")
    @GetMapping()
    public String meterdata()
    {
        return prefix + "/meterdata";
    }

    /**
     * 查询电表数据列表
     */
    @RequiresPermissions("system:meterdata:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MeterData meterData)
    {
        startPage();
        List<MeterData> list = meterDataService.selectMeterDataList(meterData);
        return getDataTable(list);
    }

    /**
     * 导出电表数据列表
     */
    @RequiresPermissions("system:meterdata:export")
    @Log(title = "电表数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MeterData meterData)
    {
        List<MeterData> list = meterDataService.selectMeterDataList(meterData);
        ExcelUtil<MeterData> util = new ExcelUtil<MeterData>(MeterData.class);
        return util.exportExcel(list, "电表数据");
    }

    /**
     * 新增电表数据
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存电表数据
     */
    @RequiresPermissions("system:meterdata:add")
    @Log(title = "电表数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MeterData meterData)
    {
        return toAjax(meterDataService.insertMeterData(meterData));
    }

    /**
     * 修改电表数据
     */
    @RequiresPermissions("system:meterdata:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        MeterData meterData = meterDataService.selectMeterDataById(id);
        mmap.put("meterData", meterData);
        return prefix + "/edit";
    }

    /**
     * 修改保存电表数据
     */
    @RequiresPermissions("system:meterdata:edit")
    @Log(title = "电表数据", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MeterData meterData)
    {
        return toAjax(meterDataService.updateMeterData(meterData));
    }

    /**
     * 删除电表数据
     */
    @RequiresPermissions("system:meterdata:remove")
    @Log(title = "电表数据", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(meterDataService.deleteMeterDataByIds(ids));
    }
    
    /**
     * 跳转到电量统计页面
     */
    @RequiresPermissions("system:meterdata:statistics")
    @GetMapping("/powerStatistics")
    public String powerStatistics()
    {
        return prefix + "/power_statistics";
    }
    
    /**
     * 按日统计用电量
     */
    @RequiresPermissions("system:meterdata:statistics")
    @PostMapping("/statisticsByDay")
    @ResponseBody
    public AjaxResult statisticsByDay(@RequestParam("startDate") String startDate,
                                     @RequestParam("endDate") String endDate)
    {
        List<Map<String, Object>> data = meterDataService.statisticsByDay(startDate, endDate);
        return AjaxResult.success(data);
    }
    
    /**
     * 按周统计用电量
     */
    @RequiresPermissions("system:meterdata:statistics")
    @PostMapping("/statisticsByWeek")
    @ResponseBody
    public AjaxResult statisticsByWeek(@RequestParam("startDate") String startDate,
                                      @RequestParam("endDate") String endDate)
    {
        List<Map<String, Object>> data = meterDataService.statisticsByWeek(startDate, endDate);
        return AjaxResult.success(data);
    }
    
    /**
     * 按月统计用电量
     */
    @RequiresPermissions("system:meterdata:statistics")
    @PostMapping("/statisticsByMonth")
    @ResponseBody
    public AjaxResult statisticsByMonth(@RequestParam("yearMonth") String yearMonth)
    {
        List<Map<String, Object>> data = meterDataService.statisticsByMonth(yearMonth);
        return AjaxResult.success(data);
    }
    
    /**
     * 按年统计用电量
     */
    @RequiresPermissions("system:meterdata:statistics")
    @PostMapping("/statisticsByYear")
    @ResponseBody
    public AjaxResult statisticsByYear(@RequestParam("startYear") String startYear,
                                      @RequestParam("endYear") String endYear)
    {
        List<Map<String, Object>> data = meterDataService.statisticsByYear(startYear, endYear);
        return AjaxResult.success(data);
    }
    
    /**
     * 按小时统计用电量
     */
    @RequiresPermissions("system:meterdata:list")
    @GetMapping("/statisticsByHour")
    @ResponseBody
    public AjaxResult statisticsByHour(String date) {
        List<Map<String, Object>> data = meterDataService.statisticsByHour(date);
        return AjaxResult.success(data);
    }
    
    /**
     * 获取最新的各时间段统计数据
     */
    @PostMapping("/getLatestStatistics")
    @ResponseBody
    public AjaxResult getLatestStatistics()
    {
        try {
            // 获取当前日期
            LocalDate today = LocalDate.now();
            String currentDate = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String currentYear = String.valueOf(today.getYear());
            
            // 获取日统计数据（当天）
            List<Map<String, Object>> dayData = meterDataService.statisticsByDay(currentDate, currentDate);
            double dayValue = 0;
            if (!dayData.isEmpty()) {
                Object energy = dayData.get(0).get("energy");
                dayValue = energy != null ? Double.parseDouble(energy.toString()) : 0;
            }
            
            // 获取周统计数据（当前周）
            LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
            String weekStart = startOfWeek.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String weekEnd = endOfWeek.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            List<Map<String, Object>> weekData = meterDataService.statisticsByWeek(weekStart, weekEnd);
            double weekValue = 0;
            if (!weekData.isEmpty()) {
                // 直接获取周统计值，SQL已经计算了最大值减最小值
                Object energy = weekData.get(0).get("energy");
                weekValue = energy != null ? Double.parseDouble(energy.toString()) : 0;
            }
            
            // 获取月统计数据（当前月）
            String currentMonthStr = today.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            List<Map<String, Object>> monthData = meterDataService.statisticsByMonth(currentMonthStr);
            double monthValue = 0;
            for (Map<String, Object> item : monthData) {
                String month = item.get("month").toString();
                if (month.equals(currentMonthStr)) {
                    Object energy = item.get("energy");
                    monthValue = energy != null ? Double.parseDouble(energy.toString()) : 0;
                    break;
                }
            }
            
            // 获取年统计数据（当前年）
            List<Map<String, Object>> yearData = meterDataService.statisticsByYear(currentYear, currentYear);
            double yearValue = 0;
            if (!yearData.isEmpty()) {
                Object energy = yearData.get(0).get("energy");
                yearValue = energy != null ? Double.parseDouble(energy.toString()) : 0;
            }
            
            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("day", dayValue);
            result.put("week", weekValue);
            result.put("month", monthValue);
            result.put("year", yearValue);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取统计数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 跳转到数据明细页面
     */
    @RequiresPermissions("system:meterdata:view")
    @GetMapping("/detail")
    public String detail()
    {
        return prefix + "/data_detail";
    }

    /**
     * 查询电表数据明细列表（按日期范围）
     */
    @RequiresPermissions("system:meterdata:list")
    @PostMapping("/dataDetail")
    @ResponseBody
    public TableDataInfo dataDetail(MeterData meterData, 
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate)
    {
        startPage();
        // 如果提供了日期参数，设置日期范围条件
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            try {
                // 设置开始时间为开始日期00:00:00
                Date beginTime = DateUtils.parseDate(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
                // 设置结束时间为结束日期23:59:59
                Date endTime = DateUtils.parseDate(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
                
                // 设置查询参数
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTime);
                params.put("endTime", endTime);
                meterData.setParams(params);
                
                // 添加系统日志打印
                System.out.println("日期范围查询参数：startDate=" + startDate + ", endDate=" + endDate);
                System.out.println("转换后的时间参数：beginTime=" + beginTime + ", endTime=" + endTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("未提供日期范围参数或参数为空");
        }
        List<MeterData> list = meterDataService.selectMeterDataList(meterData);
        System.out.println("查询结果数量：" + (list != null ? list.size() : 0));
        return getDataTable(list);
    }
    
    /**
     * 导出电表数据明细列表
     */
    @RequiresPermissions("system:meterdata:export")
    @Log(title = "电表数据明细", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDetail")
    @ResponseBody
    public AjaxResult exportDetail(MeterData meterData, 
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate)
    {
        // 如果提供了日期参数，设置日期范围条件
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            try {
                // 设置开始时间为开始日期00:00:00
                Date beginTime = DateUtils.parseDate(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
                // 设置结束时间为结束日期23:59:59
                Date endTime = DateUtils.parseDate(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
                
                // 设置查询参数
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTime);
                params.put("endTime", endTime);
                meterData.setParams(params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<MeterData> list = meterDataService.selectMeterDataList(meterData);
        ExcelUtil<MeterData> util = new ExcelUtil<MeterData>(MeterData.class);
        return util.exportExcel(list, "电表数据明细");
    }
}